package com.linjm.controller;
import com.alibaba.fastjson.JSON;
import com.linjm.bean.SkuImage;
import com.linjm.bean.SkuInfo;
import com.linjm.bean.SkuSaleAttrValue;
import com.linjm.bean.SpuSaleAttr;
import com.linjm.config.LoginRequire;
import com.linjm.service.SpuService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.HashMap;
import java.util.List;
//@CrossOrigin
@Controller
public class ItemController {
    @DubboReference
    private SpuService spuService;

    //@LoginRequire
    @RequestMapping("{skuId}.html")
    public String skuInfoPage(@PathVariable String skuId, Model model){
        SkuInfo skuInfo = spuService.getSkuInfo(skuId);
       List<SkuImage> skuImageList = spuService.getSkuImageList(skuId);
        model.addAttribute("skuInfo",skuInfo);
        model.addAttribute("skuImageList",skuImageList);
        //读取spu对应的sku数据
        List<SpuSaleAttr> saleAttrList =spuService.getSpuSaleAttrListCheckBySku(skuInfo);
        model.addAttribute("saleAttrList",saleAttrList);
        //根据spuId获取销售属性值
        List<SkuSaleAttrValue> skuSaleAttrValueList= spuService.getSpuSaleAttrListCheckBySpu(skuInfo.getSpuId());
        String key="";
        HashMap<String, Object> map = new HashMap<>();
        for (int i = 0; i < skuSaleAttrValueList.size(); i++) {
            SkuSaleAttrValue skuSaleAttrValue = skuSaleAttrValueList.get(i);
            if (key.length()>0){
               key=key+"|";
            }
            key+=skuSaleAttrValue.getSaleAttrValueId();
            //当循环停止或skuId不相同时，停止拼接，放入map,并清空
            if((i+1)==skuSaleAttrValueList.size() || !skuSaleAttrValue.getSkuId().equals(skuSaleAttrValueList.get(i+1).getSkuId()) ){
                map.put(key, skuSaleAttrValue.getSkuId());
                key="";
            }
        }
        //将map转换为字符串
        String valuesSkuJson  = JSON.toJSONString(map);
        // 保存json
        model.addAttribute("valuesSkuJson",valuesSkuJson);
        return "item";
    }

    @RequestMapping("ok")
    public String getIndex(){
        return "index";
    }

}
